﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Cherry.Agile.UI.Framework
{
    public class MemberManager
    {
        const string CurMemberInfoKey = "__ami";
        const int MaxCount = 5;
        static string CookieName
        {
            get
            {
                var key = CurMemberInfoKey.AsCookieKey();
                return key;
            }
        }

        internal const string AMKEY = "_pi";

        /// <summary>
        /// 
        /// </summary>
        public static int SelectedId
        {
            get
            {
                if (!ApplicationContext.Multiple || HttpContext.Current.Items[AMKEY] == null)
                    return 0;

                return (int)HttpContext.Current.Items[AMKEY];
            }
            internal set
            {
                HttpContext.Current.Items[AMKEY] = value;
            }

        }

        /// <summary>
        /// 重新处理Url将当前选择病人的Id附加到Url中
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ResolveUrl(string url)
        {
            return ResolveUrl(url, SelectedId);
        }

        private static string ResolveUrl(string url, int index)
        {
            if (string.IsNullOrEmpty(url) || index < 0 || !ApplicationContext.Multiple)
                return url;

            if (url.IndexOf(AMKEY + "=") < 0)
            {
                url += url.IndexOf("?") < 0 ? "?" : "&";
                url += AMKEY + "=" + index;
            }
            return url;
        }

        public static string GetDefaultPageUrl(string url)
        {
            if (url.IndexOf(AMKEY + "=") > 0 || !ApplicationContext.Multiple)
                return url;
            //var index = Index;
            //Index += 1;
            return ResolveUrl(url, SelectedId);

        }
    }
}
